package com.iflytek.iot.platform.tracing.biz;

import cn.zull.tracing.core.filter.AbstractHttpTracingRequestFilter;
import org.apache.catalina.connector.RequestFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author zurun
 * @date 2019/6/2 23:54:34
 */
@Component
public class IotHttpTracingRequestFilter extends AbstractHttpTracingRequestFilter {

    /**
     * 配置忽略的uri,使用分号隔开
     */
    @Value("${http.tracingIgnore:nothing}")
    private String tracingIgnore;

    /**
     * 规则列表
     */
    private Set<String> ignoreSets = null;

    @Override
    public boolean whetherIgnoreUri(RequestFacade requestFacade) {
        tracingIgnore = "nothing".equals(tracingIgnore) ? null : tracingIgnore;
        if (StringUtils.isNotEmpty(tracingIgnore)) {
            ignoreSets = Collections.unmodifiableSet(
                    new HashSet<>(Arrays.asList(tracingIgnore.split(";", 0))));
        } else {
            ignoreSets = Collections.emptySet();
        }
        String uri = requestFacade.getRequestURI();
        if (isMatches(ignoreSets, uri)) {
            return true;
        }
        return false;
    }

    /**
     * 匹配规则
     *
     * @param patterns 匹配规则
     * @param url      url列表
     * @return
     */
    private boolean isMatches(Set<String> patterns, String url) {
        if (null == patterns) {
            return false;
        }
        for (String str : patterns) {
            if (str.endsWith("/*")) {
                String name = str.substring(0, str.length() - 2);
                if (url.contains(name)) {
                    return true;
                }
            } else {
                Pattern pattern = Pattern.compile(str);
                if (pattern.matcher(url).matches()) {
                    return true;
                }
            }
        }
        return false;
    }
}
